package com.live.spaces.shanboli;

import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

public class WriteXML {
	private Document document;

	private String filename;

	public WriteXML() throws ParserConfigurationException {
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		document = builder.newDocument();
	}

	public void toWrite(String nickName) {
		Element root = document.createElement("JXChat2");
		document.appendChild(root);
		Element title = document.createElement("NickName");
		title.appendChild(document.createTextNode(nickName));
		root.appendChild(title);
		
	}

	public void toSave() {
		try {
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer = tf.newTransformer();
			DOMSource source = new DOMSource(document);
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			PrintWriter pw = new PrintWriter(new FileOutputStream("./com/live/spaces/shanboli/nickname.xml"));
			StreamResult result = new StreamResult(pw);
			transformer.transform(source, result);
		} catch (TransformerException mye) {
			mye.printStackTrace();
		} catch (IOException exp) {
			exp.printStackTrace();
		}
	}

	public static void main(String args[]) {
		try {
			WriteXML myxml = new WriteXML();
			myxml.toWrite("JXChat2peer8");
			myxml.toSave();
			System.out.print("Your writing is successful.");
		} catch (ParserConfigurationException exp) {
			exp.printStackTrace();
			System.out.print("Your writing is failed.");
		}
	}
}
